'use client'

import React, { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import { useSession } from 'next-auth/react'
import { toast } from 'react-hot-toast'

interface StageSubmission {
  id: string
  stageId: string
  answer: any
  score: number | null
  feedback: string | null
  submittedAt: string | null
  stage: {
    id: string
    title: string
    order: number
    content: any
    type: string
  }
}

interface Submission {
  id: string
  status: string
  score: number | null // 总分
  stageSubmissions: StageSubmission[]
  submittedAt: string // 实验总提交时间
  updatedAt: string // 应该是最后评分/更新时间
}

// Helper function to render student's answer in a readable format
const renderStudentAnswerForHistory = (stageType: string, answerString: string | null, stageContent: any) => {
  console.log('[HistoryView] Rendering answer for stageType:', stageType, 'Raw Answer String:', answerString, 'Stage Content:', stageContent);
  if (!answerString) {
    console.log('[HistoryView] No answer string provided.');
    return <span className="text-gray-500 italic">未作答</span>;
  }
  try {
    const answerObject = JSON.parse(answerString);
    console.log('[HistoryView] Parsed Answer Object:', answerObject);

    switch (stageType) {
      case 'MULTIPLE_CHOICE':
        console.log('[HistoryView] Handling MULTIPLE_CHOICE');
        const selectedOptionId = answerObject.selectedOption;
        if (selectedOptionId && stageContent?.options && Array.isArray(stageContent.options)) {
          const selectedOption = stageContent.options.find((opt: any) => opt.id === selectedOptionId);
          console.log('[HistoryView] MC - Selected Option Object:', selectedOption);
          return selectedOption ? (
            <span className="text-gray-700">{selectedOption.text}</span>
          ) : (
            <span className="text-red-500 italic">选择的选项无效</span>
          );
        }
        console.log('[HistoryView] MC - Condition not met or no selected option.');
        return <span className="text-gray-500 italic">未选择选项</span>;
      case 'FILL_IN_BLANK':
      case 'TEXT_INPUT': 
        console.log('[HistoryView] Handling FILL_IN_BLANK/TEXT_INPUT');
        return <span className="text-gray-700 whitespace-pre-wrap break-words">{answerObject.textInput || '未填写'}</span>;
      case 'FILE_UPLOAD':
        console.log('[HistoryView] Handling FILE_UPLOAD');
        if (answerObject.fileUrl && answerObject.fileName) {
            return <a href={answerObject.fileUrl} target="_blank" rel="noopener noreferrer" className="text-primary-600 hover:underline">{answerObject.fileName}</a>;
        } else if (typeof answerObject === 'string' && answerObject.startsWith('http')) { 
            return <a href={answerObject} target="_blank" rel="noopener noreferrer" className="text-primary-600 hover:underline">查看文件</a>;
        }
        return <span className="text-gray-500 italic">未上传文件或链接无效</span>;
      case 'CODE':
        console.log('[HistoryView] Handling CODE');
        return <pre className="text-xs bg-gray-800 text-white p-2 rounded-md whitespace-pre-wrap break-all">{answerObject.code || '// 未提交代码'}</pre>;
      default:
        console.log('[HistoryView] Default case, returning raw string.');
        return <pre className="text-xs bg-gray-50 p-2 rounded-md whitespace-pre-wrap break-all">{answerString}</pre>;
    }
  } catch (e) {
    console.error("[HistoryView] Failed to parse answer string in render:", answerString, e);
    return <pre className="text-xs bg-gray-50 p-2 rounded-md text-red-500 whitespace-pre-wrap break-all">无法解析答案: {answerString}</pre>;
  }
};

export default function HistoryView() {
  const params = useParams()
  const { data: session } = useSession()
  const experimentId = params.id as string
  const [history, setHistory] = useState<Submission[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!experimentId || !session?.user?.id) return

    const fetchHistory = async () => {
      setLoading(true)
      setError(null)
      try {
        const response = await fetch(`/api/experiments/${experimentId}/history?studentId=${session.user.id}`)
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}))
          throw new Error(errorData.message || `获取历史评测记录失败 (${response.status})`)
        }
        const data = await response.json()
        setHistory(data.history || [])
      } catch (err: any) {
        console.error("获取历史评测记录错误:", err)
        setError(err.message || '获取历史评测记录失败，请稍后重试。')
        toast.error(err.message || '获取历史评测记录失败')
      } finally {
        setLoading(false)
      }
    }

    fetchHistory()
  }, [experimentId, session?.user?.id])

  if (loading) {
    return (
      <div className="py-6">
        <div className="flex justify-center">
          <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary-600"></div>
        </div>
        <p className="mt-2 text-center text-gray-600">加载历史记录中...</p>
      </div>
    )
  }

  if (error) {
    return (
      <div className="py-6 bg-red-50 border border-red-200 rounded-md p-4">
        <p className="text-sm text-red-700">{error}</p>
      </div>
    )
  }

  if (history.length === 0) {
    return (
      <div className="py-10 text-center">
        <svg xmlns="http://www.w3.org/2000/svg" className="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
        </svg>
        <h3 className="mt-2 text-lg font-medium text-gray-900">暂无历史评测记录</h3>
        <p className="mt-1 text-sm text-gray-500">您尚未在此实验中提交过任何内容或进行过评测。</p>
      </div>
    )
  }

  return (
    <div className="space-y-8 py-6">
      {history.map((submission, index) => (
        <div key={submission.id || index} className="bg-white shadow overflow-hidden sm:rounded-lg">
          <div className="px-4 py-5 sm:px-6 bg-gray-50 border-b border-gray-200">
            <h3 className="text-lg leading-6 font-medium text-gray-900">
              提交记录 #{history.length - index} (提交时间: {new Date(submission.submittedAt).toLocaleString()})
            </h3>
            <p className="mt-1 max-w-2xl text-sm text-gray-500">
              总得分: {submission.score !== null ? `${submission.score} / 100` : '未评分'} | 状态: {submission.status}
            </p>
          </div>
          <div className="border-t border-gray-200 px-4 py-5 sm:p-0">
            <dl className="sm:divide-y sm:divide-gray-200">
              {submission.stageSubmissions.sort((a,b) => a.stage.order - b.stage.order).map((stageSub) => {
                let stageContentParsed: any = {};
                if (stageSub.stage.content && typeof stageSub.stage.content === 'string') {
                  try { stageContentParsed = JSON.parse(stageSub.stage.content); } catch (e) { console.error('Failed to parse stage content in HistoryView:', e); }
                } else {
                  stageContentParsed = stageSub.stage.content || {};
                }
                
                const canViewExplanationInHistory = stageContentParsed.explanationVisibleToStudent === true;

                return (
                  <div key={stageSub.id} className="py-4 sm:py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                    <dt className="text-sm font-medium text-gray-600">阶段 {stageSub.stage.order}: {stageSub.stage.title}</dt>
                    <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2 space-y-1">
                      <div>
                        <span className="font-medium">提交答案: </span>
                        {renderStudentAnswerForHistory(stageSub.stage.type, stageSub.answer, stageContentParsed)}
                      </div>
                      <p><span className="font-medium">得分: </span>{stageSub.score !== null ? `${stageSub.score}` : '未评分'} / {stageContentParsed.points || 'N/A'}</p>
                      {stageSub.feedback && <p className="mt-1 text-xs text-gray-500 italic"><span className="font-medium">教师评语: </span>{stageSub.feedback}</p>}
                      {stageSub.submittedAt && <p className="text-xs text-gray-500"><span className="font-medium">提交于: </span>{new Date(stageSub.submittedAt).toLocaleString()}</p>}
                      
                      {canViewExplanationInHistory && stageContentParsed.answerExplanation && (
                        <div className="mt-2 pt-2 border-t border-gray-100">
                          <h5 className="text-xs font-semibold text-gray-700 mb-0.5">答案解析:</h5>
                          <div 
                            className="prose prose-xs max-w-none text-gray-600"
                            dangerouslySetInnerHTML={{ __html: stageContentParsed.answerExplanation }}
                          />
                        </div>
                      )}
                    </dd>
                  </div>
                );
              })}
            </dl>
          </div>
        </div>
      ))}
    </div>
  )
} 